// VirtualDevice.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "cnComm.h"

cnComm com;
HANDLE hEvent = INVALID_HANDLE_VALUE;
void OnRecevie(void)
{
	char buffer[1024];
	unsigned int read = com.Read( buffer, 1024 );
	if( read && buffer[0] == 0x61 )
	{
		SetEvent( hEvent );
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	hEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
	com.OnReceive = OnRecevie;
	com.Open( 1, _T("9600,8,n,1") );

	FILE *fp = _tfopen( argv[1], _T("rb") );
	fseek( fp, 0, SEEK_END );
	long size = ftell(fp);
	fseek( fp, 0, SEEK_SET );

	char *memBuffer = (char*)malloc(size);
	char *memCurrent = memBuffer;
	fread( memBuffer, size, 1, fp );

	fclose(fp);

	for( char* memBegin = memCurrent = memBuffer; memCurrent < memBuffer + size; ++memCurrent )
	{
		if( *memCurrent == 0 )
		{
			puts( "ready write..." );
			WaitForSingleObject( hEvent, INFINITE );
			com.Write( memBegin, memCurrent - memBegin );
			memBegin = memCurrent;
		}
	}

	com.Close();
	CloseHandle( hEvent );
	return 0;
}

